﻿// ==================================================================================================
// Copyright(C) 2018 FI Ltd. All rights reserved.
//
// SYSTEM NAME	: FI.Net Application Framework
// COMPONENT ID	: FI.Architecture.Server
// COMPONENT DESC:		
//
// CREATED DATE/BY:		18 Aug 2018 / Tian Mi
//
// REVISION HISTORY:	DATE/BY			SR#/CS/PM#/OTHERS		DESCRIPTION OF CHANGE
// ==================================================================================================

using FI.Core.IoC;
using System;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;

namespace FI.Architecture.Server
{
    /// <summary>
    /// This class is used to define <see cref="IServiceLocator"/> specific extension methods.
    /// </summary>
    public static class ServiceLocatorExtensions
    {
        /// <summary>
        /// Registers the services.
        /// </summary>
        /// <param name="serviceLocator">The service locator.</param>
        /// <param name="excludedInterfaces">The excluded interfaces.</param>
        public static void RegisterServices(this IServiceLocator serviceLocator, params Type[] excludedInterfaces)
        {
            excludedInterfaces = excludedInterfaces ?? new Type[0];
            foreach (Assembly assembly in BuildManager.GetReferencedAssemblies())
            {
                foreach (Type type in assembly.GetTypes())
                {
                    if (type.IsAbstract)
                    {
                        continue;
                    }

                    if (!typeof(ServiceBase).IsAssignableFrom(type))
                    {
                        continue;
                    }

                    foreach (Type interfaceType in type.GetInterfaces())
                    {
                        if (excludedInterfaces.Contains(interfaceType))
                        {
                            continue;
                        }
                        serviceLocator.Register(interfaceType, type, string.Empty);
                    }
                }
            }
        }
    }
}
